import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    //存储当前用户信息
    userInfo: JSON.parse(localStorage.getItem("user")), //这里也是 把JSON字符串转换成一个对象
    //存储token字符串
    token: localStorage.getItem("token"),
  },
  getters: {},
  mutations: {
    /**
     * 当登录成功后将会得到用户信息与token字符串 调用loginOK可以将这些信息存入state
     * @param {*} state
     * @param {*} payload  {user:xxxxx,token:xxxxx}
     */
    saveUserState(state, payload) {
      state.userInfo = payload.user; //payload 是点击登录的时候传参进来的数据
      state.token = payload.token;
      //还要存入localstorage
      localStorage.setItem("token", payload.token);
      localStorage.setItem("userInfo", JSON.stringify(payload.user)); //这里的user是一个对象 要用转换成JSON字符串
    },
    /**
     * 清除 用户状态注销方法
     *
     */
    clearUserState(state) {
      state.userInfo = undefined;
      state.token = undefined;
      localStorage.clear();
    },
  },
  actions: {},
  modules: {},
});
